/**
 * l类别管理管理
 */
//'formSelects.render('permissions');
var pageCurr;
var form;

$(function() {

    layui.use('table', function(){
        var table = layui.table;
        form = layui.form;

        tableIns=table.render({
            elem: '#category1List',
            url:'/category1/category1List',
            method: 'get', //默认：get请求
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'pageNum', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response:{
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 200, //成功的状态码，默认：0
                countName: 'totals', //数据总数的字段名称，默认：count
                dataName: 'list' //数据列表的字段名称，默认：data
            },
            cols: [[
                {type:'numbers'}
                ,{field:'category1Name', title:'类别名称',align:'center'}
                ,{field:'category1Remark', title:'类别描述',align:'center'}
                //,{field:'category1Picture', title:'图片路径',align:'center'}
                , {
                    field: 'category1Picture',
                    title: '照片缩略图',
                    //width: 100,
                    align: 'center',
                    templet: function(data) {
                        //return  "<img src='"+datum.formatUrl(d.url)+"' style='height:50px;'";
                        //////
                        ///////图片展示
                        var pictureUrl=data.category1Picture;
                        var picture=pictureUrl.split("/");
                        //$('#demo1').attr('src', "http://localhost:8080/"+picture[picture.length-1]);
                        //////
                        var url =null;
                        if(data.category1Picture!=null){
                            url = "http://localhost:8080/"+picture[picture.length-1];
                        }
                        return '<a href="' + url + '" target="_blank " title="点击查看">' +
                            '<img src="' + url + '" style="height:30px;" />' +
                            '</a>';
                    }
                }


                ,{field:'ccreateTime', title:'创建时间',align:'center'}
                ,{field:'uupdateTime', title:'更新时间',align:'center'}
                ,{field:'status', title:'是否有效',align:'center'}
                ,{fixed:'right',title:'操作',align:'center', toolbar:'#optBar'}
            ]],
            done: function(res, curr, count){
                $("[data-field='status']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("有效")
                    }else if($(this).text()=='1'){
                        $(this).text("失效")
                    }
                });
                pageCurr=curr;

            }
        });


        //监听工具条
        table.on('tool(category1Table)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                //删除
                delCategory1(data,data.category1Id);
            } else if(obj.event === 'edit'){
                //编辑
                edit(data);
            }else if(obj.event === 'recover'){
                //恢复
                recoverCategory1(data,data.category1Id);
            }
        });



        //监听提交
        form.on('submit(category1Submit)', function(data){
            formSubmit(data);
            return false;
        });

    });

});

//提交表单
function formSubmit(obj){


    $.ajax({
        type: "post",
        data: $("#category1Form").serialize(),
        url: "/category1/setCategory1",
        success: function (data) {
            if (data.code == 1) {
                layer.alert(data.msg,function(){
                    layer.closeAll();
                    load(obj);
                });
            } else {
                layer.alert(data.msg);
            }
        },
        error: function () {
            layer.alert("操作请求错误，请您稍后再试",function(){
                layer.closeAll();
                load(obj);
            });
        }
    });
}

//新增
function add() {
    edit(null,"新增");
}
//打开编辑框
function edit(data,title){
    $('#demo1').attr('src', ""); //清空
    //$('#demo1').val(""); //清空
    $('#demoText').html('<span style="color: #8f8f8f;"></span>');//清空
    if(data == null){
        $("#category1Id").val("");
    }else{
        //回显数据
        $("#category1Id").val(data.category1Id);
        $("#category1Name").val(data.category1Name);
        $("#category1Remark").val(data.category1Remark);
        $("#category1Picture").val(data.category1Picture);


        ///////图片展示
       var pictureUrl=data.category1Picture;
        var picture=pictureUrl.split("/");
        $('#demo1').attr('src', "http://localhost:8080/"+picture[picture.length-1]);

    }

    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);

    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['550px','550px'],
        content:$('#setCategory1'),
        end:function(){
            cleanCategory1();
        }
    });
}

//重新加载table
function load(obj){
    tableIns.reload({
        where: obj.f
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
}

//删除
function delCategory1(obj,category1Id) {
    if(null!=category1Id){
        layer.confirm('您确定要删除吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/category1/updateCategory1Status",{"category1Id":category1Id,"status":1},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}
//恢复
function recoverCategory1(obj,category1Id) {
    if(null!=category1Id){
        layer.confirm('您确定要恢复吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/category1/updateCategory1Status",{"category1Id":category1Id,"status":0},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(){
                        layer.closeAll();
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.closeAll();
        });
    }
}


function cleanCategory1() {
    $("#category1Name").val("");
    $("#category1Remark").val("");
    $("#category1Picture").val("");
}



//图片上传
layui.use(["jquery", "upload", "form", "layer", "element"], function () {
    var url=null;
    var $ = layui.$,
        element = layui.element,
        layer = layui.layer,
        upload = layui.upload,
        form = layui.form;


    //拖拽上传
    var uploadInst = upload.render({
        elem: '#uploadImg'
        , url: '/category1/uploadImage'
        ,auto: false
        ,bindAction: '#submit0'
        , size: 500
        , choose: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.url == "null") {
                return layer.msg('上传失败');
            }else {
                //上传成功
                //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
                console.log(res.url);
                url=res.url;
                $('#category1Picture').val(url)
                //$('#category1Picture').attr('value', url); //图片链接（base64）
                //$("#category1Picture").val(res.url);
            }
            //////////////
            //swindow.parent.uploadHeadImage(res.url);
            var demoText = $('#demoText');
            demoText.html('<span style="color: #8f8f8f;">上传成功!!!</span>');
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });
    element.init();
});





